//
//  LoginViewController.m
//  sharedBooks
//
//  Created by XunFengKJ on 2016/11/9.
//  Copyright © 2016年 XunFengKJ. All rights reserved.
//

#import "LoginViewController.h"
#import "XFForgetPassWordViewController.h"
#import "BookShareUserInforDefault.h"
#import "SBRegisterViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "XFTarbarViewController.h"
#import "testPictureUp.h"

@interface LoginViewController ()
//头像
@property (weak, nonatomic) IBOutlet UIImageView *iconImageView;
//密码
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
//登录
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@end

@implementation LoginViewController
#pragma mark - life
-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    self.fd_interactivePopDisabled = YES;
    [super viewDidLoad];
    self.view.backgroundColor = lColorWhite;
    if (![NSString isBlankString:[XFKeychainTool readUserName]] ) {
        self.accountTextFiled.text = [XFKeychainTool readUserName];
    }
    if (![NSString isBlankString:[XFKeychainTool readPassword]] ) {
        self.passwordTextField.text = [XFKeychainTool readPassword];
    }
}

#pragma mark - setUI
-(void)initViews{
    [super initViews];
    [self setUpBtnLayerWithBtn:self.loginBtn color:nil borderWidth:0 cornerRadius:SCREEN_HEIGHT*0.035];
    self.iconImageView.layer.cornerRadius = 10.0f;
    self.iconImageView.layer.masksToBounds = YES;
}

//设置按钮边框
-(void)setUpBtnLayerWithBtn:(UIButton*)btn color:(UIColor*)color borderWidth:(CGFloat)borderWidth cornerRadius:(CGFloat)cornerRadius{
    
    btn.layer.borderColor = [color == nil?XFUIColorFromRGB(0xFFFFFF):color CGColor];

    btn.layer.borderWidth = borderWidth;
    btn.layer.cornerRadius = cornerRadius;
}

#pragma MARK - 点击事件
//忘记密码
- (IBAction)forgetPassWordBtnClick:(id)sender {
    XFForgetPassWordViewController *forgetP = [XFForgetPassWordViewController new];
    forgetP.isFromLoginVC = YES;
    [self.navigationController pushViewController:forgetP animated:YES];
    //    [self.navigationController pushViewController:[ScanningViewController new]animated:YES];
    //    [XFPostRequest postRequestTestCookieuserCode:@"2222" success:^(id responseObject) {
    //        LGFLog(@"testCookie -responseObject - %@",responseObject);
    //    } failure:^(NSError *error) {
    //        LGFLog(@"testCookie -error - %@",error);
    //    }];
}

//登录
- (IBAction)loginBtnClick:(id)sender {
//    [UIApplication sharedApplication].keyWindow.rootViewController = [XFTarbarViewController new];
    //
    if (self.accountTextFiled.text.length == 0) {
        [SOAutoHideMessageView showMessage:@"请输入账号" inView:self.view];
    }else if (self.passwordTextField.text.length == 0){
        [SOAutoHideMessageView showMessage:@"请输入密码" inView:self.view];
    }else{
        
        NSString *passW = self.passwordTextField.text.md5TolowercaseString;
        [self.accountTextFiled resignFirstResponder];
        [self.passwordTextField resignFirstResponder];
        [MBProgressHUD showMessage:@"登录中..." toView:self.view dissmissTime:0];
        WEAKSELF
        [XFPostRequest postRequestLoginUsername:self.accountTextFiled.text Password:passW success:^(id responseObject) {
            LGFLog(@"登录 - %@",responseObject);
            [MBProgressHUD hideHUDForView:weakSelf.view];
            //登录成功
            [SOAutoHideMessageView showMessage:responseObject[@"msg"] inView:weakSelf.view];
            if ([responseObject[@"status"] intValue] == 200) {
//                [self.navigationController pushViewController:[testPictureUp new] animated:YES];
                NSArray *secondUser = [[responseObject safeJsonObjectForKey:@"content"] safeJsonObjectForKey:@"roles"];
                if (secondUser.count) {
                    NSDictionary *dict = secondUser[0];
                    [BookShareUserInforDefault saveiscanOpenSecondUser:[dict safeJsonObjectForKey:@"name"]];
                }
                NSArray *dataArr =[[responseObject safeJsonObjectForKey:@"content"] safeJsonObjectForKey:@"shops"];
                if (dataArr.count>0) {
                    NSDictionary *data = dataArr[0];
                    [weakSelf saveUserDataWithDict:data];
                }
               
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.75 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    XFTarbarViewController *tarBarVC =[XFTarbarViewController new];
                        [UIApplication sharedApplication].keyWindow.rootViewController = tarBarVC;
                });
                //极光
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    NSString *alias =  [NSString stringWithFormat:@"%@",[[responseObject safeJsonObjectForKey:@"content"] safeJsonObjectForKey:@"id"]];
                    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
                        LGFLog(@"iResCode-%zd alias = %@",iResCode,alias);
                    }];
                });
                
                //保存账号
                [XFKeychainTool saveUserName:weakSelf.accountTextFiled.text];
                [XFKeychainTool savePassword:weakSelf.passwordTextField.text];
            }else{
                [SOAutoHideMessageView showMessage:[responseObject safeJsonObjectForKey:@"msg"] inView:weakSelf.view];
            }
        } failure:^(NSError *error) {
            LGFLog(@"error - %@",error);
            [MBProgressHUD hideHUDForView:weakSelf.view];
            [SOAutoHideMessageView showMessage:LNETWORKERROR inView:weakSelf.view];
        }];
    }
}

-(void)saveUserDataWithDict:(NSDictionary*)contentDict{
    
    [BookShareUserInforDefault saveLoginStatus:YES];
    [BookShareUserInforDefault saveUserAvatarUrl:[contentDict safeJsonObjectForKey:@"imanges"]];
    [BookShareUserInforDefault saveUserAddress:[contentDict safeJsonObjectForKey:@"address"]];
    [BookShareUserInforDefault saveUserBegin:[contentDict safeJsonObjectForKey:@"begin"]];
    [BookShareUserInforDefault saveUserEnd:[contentDict safeJsonObjectForKey:@"end"]];
    [BookShareUserInforDefault saveUserUid:[contentDict safeJsonObjectForKey:@"id"]];
    [BookShareUserInforDefault saveUserIntro:[contentDict safeJsonObjectForKey:@"intro"]];
    [BookShareUserInforDefault saveUserNicknames:[contentDict safeJsonObjectForKey:@"name"]];
    [BookShareUserInforDefault saveUserPhone:[contentDict safeJsonObjectForKey:@"phoneNumber"]];
}

@end
